from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from email.utils import formatdate
import os
import hashlib
import logging
import time

ENV_DEVELOPMENT_PREFIX = "http://localhost"

class BaseController(webapp.RequestHandler):
	
	def initialize(self, request, response):
		webapp.RequestHandler.initialize(self, request, response)
		self.errors = []
		self.user = users.get_current_user()
		self.is_admin = users.is_current_user_admin()
		self.is_debug = self.get_debug_flag()
		self.is_development = self.is_development()
		self.secure_token = self.get_secure_token()
		self.template_path = "templates/web"
		self.display = {}

	def is_development(self):
		return self.request.url.startswith(ENV_DEVELOPMENT_PREFIX)

	def set_cookie(self, name, value, path="/", expires_seconds=0):
		cookie_str = "%s=%s; path=%s;" % (name, value, path)
		if expires_seconds > 0:
			abs_seconds = time.time() + expires_seconds
			expires_datestr = formatdate(abs_seconds)
			cookie_str = "%s expires=%s;" % (cookie_str, expires_datestr)
		self.response.headers.add_header("Set-Cookie", cookie_str)

	def set_debug_flag(self, debug_on=False):
		logging.info("Debug: %s", str(debug_on))
		self.set_cookie("debug", str(int(debug_on)))

	def get_debug_flag(self):
		if self.is_development() or users.is_current_user_admin(): # TODO: or self.is_debug_ip()
			enable_debug = self.request.get("enable_debug", None)
			if enable_debug == "1":
				self.set_debug_flag(True)
				return True
			elif enable_debug == "0":
				self.set_debug_flag(False)
				return False
			else:
				return self.request.cookies.get("debug") == "1"
		return False

	def get_secure_token(self):
		return hashlib.md5(self.request.url).hexdigest()

	def set_global_display_variables(self):
		self.display["errors"] = self.errors
		self.display["secure_token"] = self.secure_token
		self.display["is_admin"] = self.is_admin
		self.display["is_debug"] = self.is_debug
		self.display["is_development"] = self.is_development
		self.display["is_production"] = not self.is_development
		self.display["controller"] = self.__class__.__name__
		self.display["request_url"] = self.request.url
		self.display["request_path"] = self.request.path,
		self.display["request_query_string"] = self.request.query_string
		self.display["user"] = self.user

	def render_json(self):
		return ""

	def render_template(self, template_name):
		root_path = os.path.dirname(__file__)
		if root_path.endswith("/core"):
			root_path = root_path[:-5]
		template_file = template_name + ".html" 
		render_path = os.path.join(root_path, self.template_path, template_file)
		self.set_global_display_variables()
		return template.render(render_path, self.display)
